package com.geek2.supermarket.controller;

import com.geek2.supermarket.pojo.SmbmsRole;
import com.geek2.supermarket.pojo.SmbmsUser;
import com.geek2.supermarket.service.UserService;
import com.geek2.supermarket.util.JsonResult;
import com.geek2.supermarket.util.PageSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@SessionAttributes(value = {"userSession", "roleList"}) //扩大其作用域
@Controller
@RequestMapping("/user/")
public class UserController {

    @Autowired
    @Qualifier("userService")
    private UserService userService;


    @RequestMapping("login")
    public String list(HttpServletRequest request, String userCode, String password, Model model) {
        if (userCode != null) {

            SmbmsUser smbmsUser = userService.queryUser(userCode, null);
            if (smbmsUser != null && password.equals(smbmsUser.getUserPassword())) {
                List<SmbmsRole> smbmsRoles = userService.queryRole();

                HttpSession session = request.getSession();
                session.setAttribute("username", smbmsUser.getUserName());
                System.out.println("登录中==================" + smbmsUser.getUserName());
                model.addAttribute("roleList", smbmsRoles);
                model.addAttribute("userSession", smbmsUser);
                return "/WEB-INF/jsp/frame";
            }
        }

        model.addAttribute("error", "用户名或密码错误");
        System.out.println("账号/密码错误===========" + userCode + "==" + password);
        return "forward:/index.jsp";
    }

    // 修改密码
    @RequestMapping("pwdmodify")
    public String modifyPasswork(String newpassword, String userId, Model model) {
        System.out.println("修改密码==============");
        SmbmsUser smbmsUser = new SmbmsUser();
        smbmsUser.setUserPassword(newpassword);
        smbmsUser.setId(Integer.parseInt(userId));
        System.out.println("============" + smbmsUser.toString());
        if (userService.updateUserPwd(smbmsUser)) {
            model.addAttribute("message", "修改成功");
            return "/WEB-INF/jsp/pwdmodify";
        }
        model.addAttribute("message", "修改失败");
        return "/WEB-INF/jsp/user/pwdmodify";
    }

    @RequestMapping("toPwdmodify")
    public String toPwdmodify() {
        return "/WEB-INF/jsp/user/pwdmodify";
    }

    @RequestMapping("toUseradd")
    public String touseradd() {
        return "/WEB-INF/jsp/user/useradd";
    }

    @RequestMapping("logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.removeAttribute("username");
        System.out.println("已登出");
        return "/index";
    }

    @RequestMapping("toModifyUser")
    public String toModifyUser(String userid, Model model) {
        SmbmsUser smbmsUser = userService.queryUser(null, userid);

        System.out.println("================toModifyUser:" + smbmsUser.toString());
        model.addAttribute("user", smbmsUser);
        return "/WEB-INF/jsp/user/usermodify";
    }


    @RequestMapping("queryAll")
    public String queryAllUser(String queryname, String queryUserRole, String pageIndex, Model model) {
        System.out.println("queryAll=====:" + queryname + "=======:" + queryUserRole);
        int roleId = 0;
        int currentPageNo = 1;
        int pageSize = 3;
        if (queryUserRole != null && !"".equals(queryUserRole)) {
            roleId = Integer.parseInt(queryUserRole);
        }
        if (pageIndex != null) {
            currentPageNo = Integer.parseInt(pageIndex);
        }

        //总数量（表）
        int totalCount = userService.getUserCount(queryname, roleId);

        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
        //总页数（表）
        int totalPageCount = pageSupport.getTotalPageCount();
        List<SmbmsUser> smbmsUsers = userService.queryAll(queryname, roleId, currentPageNo, pageSize);

        model.addAttribute("userList", smbmsUsers);
        model.addAttribute("totalCount", totalCount);
        model.addAttribute("currentPageNo", currentPageNo);
        model.addAttribute("totalPageCount", totalPageCount);
        model.addAttribute("queryUserName", queryname);
        model.addAttribute("queryUserRole", queryUserRole);
        return "/WEB-INF/jsp/user/userlist";
    }

    @RequestMapping("useradd")
    public String useradd(SmbmsUser smbmsUser) {
        System.out.println(smbmsUser.toString());
        boolean result = userService.addUser(smbmsUser);
        return "/WEB-INF/jsp/user/userlist";
    }

    @RequestMapping("querybyId")
    public String querybyId(String userid, Model model) {
        SmbmsUser smbmsUser = userService.queryUser(null, userid);
        if (smbmsUser != null) {
            model.addAttribute("user", smbmsUser);
            return "/WEB-INF/jsp/user/userview";
        }
        return "forward:/index.jsp";
    }

    @RequestMapping("updateUser")
    public String updateUser(SmbmsUser smbmsUser, Model model) {
        System.out.println("============修改用户");
        System.out.println("================" + smbmsUser.toString());
        boolean b = userService.updateUser(smbmsUser);
        if (b) {
            smbmsUser = userService.queryUser(null, smbmsUser.getId());
            if (smbmsUser != null) {
                model.addAttribute("user", smbmsUser);
                return "/WEB-INF/jsp/user/userview";
            }
        }
        return "forward:/index.jsp";
    }

    @RequestMapping("delById")
    @ResponseBody
    public JsonResult delById(String userid) {
        boolean result = userService.delUserById(userid);
        if (result) {
            return new JsonResult().message("删除成功").success(true);
        }
        return new JsonResult().message("未知原因删除失败").success(false);

    }

    @RequestMapping("showRole")
    @ResponseBody
    public List<SmbmsRole> showRole() {
        List<SmbmsRole> smbmsRoles = userService.queryRole();
        return smbmsRoles;
    }

}

